package org.robot.scm.platform.server.handler;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.robot.scm.pojos.platform.sqlite.MyDebts;
import org.robot.scm.utils.JsonHelper;
import org.robot.scm.utils.SQLiteUtil;

/**
 * 记账管理
 */
@Slf4j
@NoArgsConstructor
public class DebtsHandler extends BaseHandler implements HttpHandler {

    @Override
    public String getUri() {
        return "/debts";
    }

    @Override
    public void handle(HttpExchange exchange) throws IOException {
        List<MyDebts> myDebts = SQLiteUtil.query("SELECT * FROM my_debts order by debts_id desc limit 1", MyDebts.class);
        if (CollectionUtils.isNotEmpty(myDebts)) {
            MyDebts myDebt = myDebts.get(0);
            myDebt.setDebtsDate(myDebt.getDebtsDate().replaceAll("-", ""));
            Map<String, String> map = JsonHelper.toMap(JsonHelper.toJSONString(myDebt));
            map.put("debtsCount", String.valueOf(SQLiteUtil.count(MyDebts.class)));
            sendSuccessResponse(exchange, "查询成功", JsonHelper.toJSONString(map));
            return;
        }
        sendFailureResponse(exchange, "暂无信息");
    }
}
